using System;
using System.Collections;
using System.Collections.Generic;
using com.yoozoo.gta.Extension.UGUI.ScreenOrientationEx;
using LogSystem;
using Mopsicus.Plugins;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.Gta.Common;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta.Extension
{
    public class ChatAssistant : MonoBehaviour
    {
	    [SerializeField]
        private MobileInputField mobileInputField;
	    [SerializeField]
	    private RectTransform inputArea;
	    [SerializeField]
	    private RectTransform msgArea;
	    [SerializeField]
	    private RectTransform emptyArea;
	    [SerializeField] // 聊天列表的背景图，msgArea变换更新时，emptyArena也得更新
	    private RectTransform operateArea;
	    [SerializeField]
	    private Vector2 landscapeOffset;
	    [SerializeField]
	    private Vector2 portaitOffset;
	    [SerializeField]
	    private Vector2 msgAreaOffset;
	    [SerializeField]
	    private Vector2 emptyAreaOffset;
	    [SerializeField]
	    private Vector2 inputAreaOffset;
	    [SerializeField]
	    private Vector2 inputOriginSizeDelta;
	    [SerializeField]
	    private int lineHeight = 34;
        
        
#if !UNITY_EDITOR && UNITY_ANDROID
        private AndroidJavaClass javaClass;
#endif
		// 私有变量
        private RectTransform _transform;
        private RectTransform _inputTransform;
        private float scaleFactor = 1f;
        private float realScaleFactor = 1f;
        private Vector2 initPos;
        private int keyboardHeight = 0;
        private int padding = 12;
        private bool isHeightZeroLocked = false;
        
        private Vector2 inputOriginPos;
        private Vector2 inputFieldOriginSizeDelta;
        private Vector2 msgOriginPos;
        private Vector2 msgOriginSizeDelta;
        private Vector2 emptyOriginPos;
        private Vector2 emptyOriginSizeDelta;
        private Vector2 msgAreaKeyboardPos;
        private Vector2 msgAreaKeyboardSizeDelta;
        private Vector2 operateOriginPos;
        
        // 日志开关
        private string TAG = "[C#] ChatAssistant - ";
        
        /// <summary>
        /// 初始化固定变量
        /// </summary>
        void OnEnable()
        {
#if !UNITY_EDITOR && UNITY_ANDROID
            this.javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
#endif
            _transform = this.GetComponent<RectTransform> ();
            _inputTransform = mobileInputField.GetComponent<RectTransform>();
            scaleFactor = ResidentHandler.Inst.RootCanvasComponent.scaleFactor;
            initPos = _transform.anchoredPosition;
            inputFieldOriginSizeDelta = _inputTransform.sizeDelta;
            
            // 注册键盘高度变化事件
            MobileInput.OnShowKeyboard += OnKeyboardHeightChanged;

            if (inputArea)
	            inputOriginPos = inputArea.anchoredPosition;
            else
	            inputOriginPos = Vector2.zero;

            if (msgArea)
            {
	            msgOriginPos = msgArea.anchoredPosition;
	            msgOriginSizeDelta = msgArea.sizeDelta;
            }
            else
            {
	            msgOriginPos = Vector2.zero;
	            msgOriginSizeDelta = Vector2.zero;
            }
            msgAreaKeyboardPos = msgOriginPos;
            msgAreaKeyboardSizeDelta = msgOriginSizeDelta;

            if (emptyArea)
            {
	            emptyOriginPos = emptyArea.anchoredPosition;
	            emptyOriginSizeDelta = emptyArea.sizeDelta;
            }
            else
            {
	            emptyOriginPos = Vector2.zero;
	            emptyOriginSizeDelta = Vector2.zero;
            }
            
            if (operateArea)
	            operateOriginPos = operateArea.anchoredPosition;
			else
	            operateOriginPos = Vector2.zero;

            Debug.Log(LogModule.Chat, string.Format(
	            "{0} OnEnable initPos = ({1}, {2}), inputOriginPos = ({3}, {4}), msgOriginPos = ({5}, {6})",
	            TAG, initPos.x, initPos.y, inputOriginPos.x, inputOriginPos.y, msgOriginPos.x, msgOriginPos.y));
        }

        private void OnDisable()
        {
	        MobileInput.OnShowKeyboard -= OnKeyboardHeightChanged;
	        
	        Debug.Log(LogModule.Chat, string.Format(
		        "{0} OnDisable initPos = ({1}, {2}), inputOriginPos = ({3}, {4}), msgOriginPos = ({5}, {6})",
		        TAG, initPos.x, initPos.y, inputOriginPos.x, inputOriginPos.y, msgOriginPos.x, msgOriginPos.y));
        }

        public void UpdateMsgArea(int line)
        {
	        if (msgArea)
	        {
		        var height = (line - 1) * lineHeight;
		        msgArea.sizeDelta = new Vector2(msgAreaKeyboardSizeDelta.x, msgAreaKeyboardSizeDelta.y - height);
	        }
        }

        public void SetHeightZeroLocked(bool isLocked)
        {
	        isHeightZeroLocked = isLocked;
        }
        
        public void UpdateKeyboardHeight(int height)
		{
	        OnKeyboardHeightChanged(true, height, Screen.height, Screen.width);
		}

        private void OnKeyboardHeightChanged(bool isShow, int height, int layoutHeight, int layoutWidth)
        {
	        if (height == keyboardHeight) return;

	        keyboardHeight = height;
	        
	        bool isPortait = ScreenOrientManager.GetInstance().GetScreenOrientationIsPortrait();
	        
	        realScaleFactor = (float)layoutHeight / Screen.height;
	        GetScaleFactor();
	        
	        Debug.Log(LogModule.Chat, string.Format(
		        "{0} OnKeyboardHeightChanged height = {1}, layoutHeight = {2}, Screen.height = {3} [scaleFactor = {4}, realScaleFactor = {5}]",
			        TAG, height, layoutHeight, Screen.height, scaleFactor, realScaleFactor));

	        //复位到初始位置
	        if (height == 0)
	        {
		        if (isHeightZeroLocked) return;
		        
		        // 聊天输入框位置调整
		        _transform.anchoredPosition = initPos;
		        
		        if (inputArea)
		        {
			        // 重置偏移
			        inputArea.anchoredPosition = new Vector2(inputOriginPos.x , inputOriginPos.y);
		        }

		        msgArea.anchoredPosition = msgOriginPos;
		        msgArea.sizeDelta = msgOriginSizeDelta;
		        msgAreaKeyboardPos = msgOriginPos;
		        msgAreaKeyboardSizeDelta = msgOriginSizeDelta;

		        emptyArea.anchoredPosition = emptyOriginPos;
		        emptyArea.sizeDelta = emptyOriginSizeDelta;
		        
		        Debug.Log(LogModule.Chat, string.Format(
			        "{0} OnKeyboardHeightChanged 复位到初始位置 _transform = ({1}, {2}), inputArea = ({3}, {4}), msgArea = ({5}, {6})",
			        TAG, _transform.anchoredPosition.x, _transform.anchoredPosition.y, 
			        inputArea.anchoredPosition.x, inputArea.anchoredPosition.y, 
			        msgArea.anchoredPosition.x, msgArea.anchoredPosition.y));
	        }
	        else
	        {
				// 适配后的高度
		        float scaleHeight = (float)height / scaleFactor / realScaleFactor;
		        
		        Debug.Log(LogModule.Chat, string.Format(
			        "{0} OnKeyboardHeightChanged 聊天输入框位置调整 initPos.x = {1}, initPos.y = {2}, height = {3}, scaleFactor = {4}, realScaleFactor = {5}, scaleHeight = {6}",
			        TAG, initPos.x, initPos.y, height, scaleFactor, realScaleFactor, scaleHeight));
		        
		        // 聊天输入框位置调整
		        _transform.anchoredPosition = new Vector2(initPos.x, initPos.y + scaleHeight);
		        
		        //竖屏模式下不需要调整输入框
		        if (inputArea)
		        {
			        // 设置一次偏移
			        if (isPortait) {
				        inputArea.anchoredPosition = new Vector2(inputOriginPos.x, inputOriginPos.y - portaitOffset.y);
			        }
			        else
			        {
				        inputArea.anchoredPosition = new Vector2(inputOriginPos.x, inputOriginPos.y - landscapeOffset.y);
			        }
		        }
		        
		        Debug.Log(LogModule.Chat, string.Format(
			        "{0} OnKeyboardHeightChanged msgArea设置一次偏移 Screen.height = {1}, Screen.width = {2}, height = {3}, scaleFactor = {4}, msgOriginPos.y = {5}, msgAreaOffset.y = {6}, msgAreaOffset.y/scaleFactor = {7}",
					TAG, Screen.height, Screen.width, height, scaleFactor, msgOriginPos.y, msgAreaOffset.y, msgAreaOffset.y/scaleFactor));

		        // 设置一次偏移
		        if (msgArea)
		        {
			        msgAreaKeyboardPos = new Vector2(msgOriginPos.x, msgOriginPos.y - scaleHeight);
			        msgArea.anchoredPosition = msgAreaKeyboardPos;
			        if (isPortait)
			        {
				        msgAreaKeyboardSizeDelta = new Vector2(msgOriginSizeDelta.x + portaitOffset.x,
					        msgOriginSizeDelta.y + portaitOffset.y - scaleHeight);
			        }
			        else
			        {
				        msgAreaKeyboardSizeDelta = new Vector2(msgOriginSizeDelta.x + landscapeOffset.x,
					        msgOriginSizeDelta.y + landscapeOffset.y - scaleHeight);
			        }
			        msgArea.sizeDelta = msgAreaKeyboardSizeDelta;
		        }

		        if (emptyArea)
		        {
			        emptyArea.anchoredPosition = new Vector2(emptyOriginPos.x, emptyOriginPos.y - scaleHeight);
			        if (isPortait)
			        {
				        emptyArea.sizeDelta = new Vector2(emptyOriginSizeDelta.x + portaitOffset.x, 
					        emptyOriginSizeDelta.y + portaitOffset.y - scaleHeight);
			        }
			        else
			        {
				        emptyArea.sizeDelta = new Vector2(emptyOriginSizeDelta.x + landscapeOffset.x, 
					        emptyOriginSizeDelta.y + landscapeOffset.y - scaleHeight);
			        }
		        }
		        
		        Debug.Log(LogModule.Chat, string.Format(
			        "{0} OnKeyboardHeightChanged 输入框位置调整 _transform = ({1}, {2}), inputArea = ({3}, {4}), msgArea = ({5}, {6})",
			        TAG, _transform.anchoredPosition.x, _transform.anchoredPosition.y, 
			        inputArea.anchoredPosition.x, inputArea.anchoredPosition.y, 
			        msgArea.anchoredPosition.x, msgArea.anchoredPosition.y));
	        }
        }
        
        private void GetScaleFactor()
		{
			Vector2Int screenSize = ScreenOrientManager.GetInstance().GameViewSize();
			CanvasScaler canvasscaler = GetComponentInParent<CanvasScaler>();
			float resolutionX = canvasscaler.referenceResolution.x;
			float resolutionY = canvasscaler.referenceResolution.y;
			float scaleX = screenSize.x / resolutionX;
			float scaleY = screenSize.y / resolutionY;
			scaleFactor = math.min(scaleX, scaleY);
			
			Debug.Log(LogModule.Chat, string.Format(
				"{0} GetScaleFactor 计算缩放因子 resolutionX = {1}, resolutionY = {2}, scaleX = {3}, scaleY = {4}, scaleFactor = {5}",
				TAG, resolutionX, resolutionY, scaleX, scaleY, scaleFactor));
		}

        /// <summary>
        /// 获取虚拟键盘高度.
        /// </summary>
        private int GetKeyboardHeight()
        {
#if !UNITY_EDITOR
	#if UNITY_ANDROID
		AndroidJavaObject View = this.javaClass.GetStatic<AndroidJavaObject>("currentActivity").
			Get<AndroidJavaObject>("mUnityPlayer").Call<AndroidJavaObject>("getView");

		using(AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect")) {
			View.Call("getWindowVisibleDisplayFrame", Rct);
			return Screen.height - Rct.Call<int>("height");
		}
	#elif UNITY_IOS
		return (int)TouchScreenKeyboard.area.height;
	#else
		return 0;
	#endif
#else
        return 0;
#endif
        }
    }
}
